package linc.fun.openai.service.impl;

import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import linc.fun.openai.domain.dto.query.ChatRoomPageQuery;
import linc.fun.openai.domain.entity.chat.ChatMessageDO;
import linc.fun.openai.domain.entity.chat.ChatRoomDO;
import linc.fun.openai.domain.vo.ChatRoomVO;
import linc.fun.openai.handler.converter.ChatRoomConverter;
import linc.fun.openai.mapper.ChatRoomMapper;
import linc.fun.openai.service.ChatRoomService;
import linc.fun.openai.util.ChatUserUtil;
import linc.fun.openai.util.IdGenerator;
import linc.fun.openai.util.PageUtil;
import linc.fun.openai.util.WebUtil;
import org.springframework.stereotype.Service;

import static linc.fun.openai.domain.entity.chat.table.Tables.ChatRoom;

/**
 * @author linc
 * @date 2023-3-27
 * 聊天室业务实现类
 */
@Service
public class ChatRoomServiceImpl extends ServiceImpl<ChatRoomMapper, ChatRoomDO> implements ChatRoomService {
    @Resource
    private IdGenerator idGenerator;

    @Override
    public Page<ChatRoomVO> pageChatRoom(ChatRoomPageQuery query) {
        QueryWrapper queryWrapper = QueryWrapper.create().orderBy(ChatRoom.Id.desc());
        Page<ChatRoomDO> page = this.page(new Page<>(query.getPageNum(), query.getPageSize()), queryWrapper);
        return PageUtil.toPage(page, ChatRoomConverter.INSTANCE.entityToVO(page.getRecords()));
    }

    @Override
    public ChatRoomDO createChatRoom(ChatMessageDO chatMessageDO) {
        ChatRoomDO chatRoom = new ChatRoomDO();
        chatRoom.setId(idGenerator.getId());
        chatRoom.setApiType(chatMessageDO.getApiType());
        chatRoom.setIp(WebUtil.getIp());
        chatRoom.setFirstChatMessageId(chatMessageDO.getId());
        chatRoom.setFirstMessageId(chatMessageDO.getMessageId());
        // 取一部分内容当标题，可以通过 GPT 生成标题
        chatRoom.setTitle(StrUtil.sub(chatMessageDO.getContent(), 0, 50));
        chatRoom.setUserId(ChatUserUtil.getUserId());
        this.save(chatRoom);
        return chatRoom;
    }
}
